﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Json;

namespace Common
{
    public partial class SLDataGrid : UserControl
    {
        

        public Style DataGridStyle
        {
            get
            {
                return this.dataGrid.Style;
            }
            set
            {
                this.dataGrid.Style = value;
            }
        }

        public Visibility BackVisibility
        {
            get
            {
                return this.backBorder.Visibility;
            }

            set
            {
                this.backBorder.Visibility = value;
            }
        }

        public string FUNC_TYPE
        {
            get
            {
                return func_type;
            }
            set
            {
                func_type = value;
            }
        }

        public List<string> Params
        {
            get
            {
                return parameters;
            }
        }

        public List<int> HiddenColumns
        {
            get
            {
                return this.hiddens;
            }
        }

        public string TypeName
        {
            get
            {
                return this.typeName;
            }
            set
            {
                this.typeName = value;
            }
        }

        public DataGrid DataGrid
        {
            get
            {
                return this.dataGrid;
            }
        }

        public bool IsCustomerBinding
        {
            get;
            set;
        }

        string func_type = "";
        string typeName = "";
        List<string> parameters = new List<string>();
        List<int> hiddens = new List<int>();

        public delegate void DataBindingCompletedHandler();
        public event DataBindingCompletedHandler DataBindingCompleted;

        public delegate void CustomerBindingHandler(string jsonData);
        public event CustomerBindingHandler CustomerBinding;

        public DownloadStringCompletedEventHandler downloadStringCompleted;
        public UploadStringCompletedEventHandler uploadStringCompleted;
        public SLDataGrid()
        {
            InitializeComponent();
            downloadStringCompleted += new DownloadStringCompletedEventHandler(DownLoadStringCompleted);
            uploadStringCompleted += new UploadStringCompletedEventHandler(UploadStringCompleted);
            DataBindingCompleted += new DataBindingCompletedHandler(SLDataGrid_DataBindingCompleted);

            this.dataGrid.AutoGenerateColumns = false;       
        }
        
        public void FillDataGrid()
        {
            this.backBorder.Visibility = Visibility.Visible;
            CommonAPI.InvokeWebAPIByPost(uploadStringCompleted, func_type, (string)this.Tag, Params.ToArray());
        }

        protected virtual void SLDataGrid_DataBindingCompleted()
        {
            for (int i = 0; i < this.hiddens.Count; i++)
            {
                this.DataGrid.Columns[HiddenColumns[i]].Visibility = Visibility.Collapsed;
            }
        }

        private void DownLoadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            this.backBorder.Visibility = Visibility.Collapsed;
            if (e.Error == null)
            {
                Result result = CommonAPI.GetResut(e.Result);
                if (!result.result)
                {
                    // Error 처리
                    //SL_Meta.Ctrls.MainPage.msgBox.ShowMsgBox(result.error);
                    return;
                }

                char sep = (char)127;
                if (result.data == null || result.data == "")
                    return;

                Tokenizer token = new Tokenizer(result.data);

                int row_cnt = int.Parse(token.StrTok(sep));
                int col_cnt = int.Parse(token.StrTok(sep));

                dataGrid.Columns.Clear();
                List<string> cols = new List<string>();
                for (int i = 0; i < col_cnt; i++)
                {
                    DataGridTextColumn column = new DataGridTextColumn();
                    string sCaption = token.StrTok(sep);
                    if (sCaption.Length > 1)
                    {
                        switch (sCaption.Substring(0, 2))
                        {
                            case "_Y":
                            case "_F":
                            case "_T":
                            case "_B":
                                {
                                    sCaption = sCaption.Remove(0, 2);
                                }
                                break;
                        }
                    }

                    Binding b = new Binding();
                    b.ConverterParameter = sCaption;
                    b.Converter = (IValueConverter)new RowIndexConverter();
                    column.Header = sCaption;
                    column.Binding = b;
                    cols.Add(sCaption);
                    dataGrid.Columns.Add(column);
                }

                sep = (char)128;
                var rows = new System.Collections.ObjectModel.ObservableCollection<Row>();
                for (int i = 0; i < row_cnt; i++)
                {
                    Row row = new Row();

                    for (int j = 0; j < cols.Count; j++)
                    {
                        row[cols[j]] = token.StrTok(sep);
                    }
                    rows.Add(row);
                    //System.Reflection.ConstructorInfo construct = Type.GetType(typeName).GetConstructor(new Type[0]);
                    //object obj = construct.Invoke(new object[0]);
                    //System.Reflection.MethodInfo method = obj.GetType().GetMethod("SetData");
                    //if (method != null)
                    //{
                    //    method.Invoke(obj, new object[1] { token });
                    //    lists.Add(obj);
                    //}
                }
                dataGrid.ItemsSource = rows;


                
                DataBindingCompleted();

                
            }
        }

        private void UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            this.backBorder.Visibility = Visibility.Collapsed;
            if (e.Error == null)
            {
                Result result = CommonAPI.GetResut(e.Result);
                if (!result.result)
                {
                    // Error 처리
                    //SL_Meta.Ctrls.MainPage.msgBox.ShowMsgBox(result.error);
                    return;
                }
                
                if (result.data == null || result.data == "")
                    return;


                if (IsCustomerBinding)
                {
                    CustomerBinding(result.data);
                    DataBindingCompleted();
                    return;
                }

                JsonObject jObject = (JsonObject)JsonObject.Parse(result.data);
                if (!jObject.ContainsKey("column_header"))
                    return;

                JsonArray jArray = (JsonArray)jObject["column_header"];
                int col_cnt = jArray.Count;

                dataGrid.Columns.Clear();
                for (int i = 0; i < col_cnt; i++)
                {
                    DataGridTextColumn column = new DataGridTextColumn();
                    Binding b = new Binding();
                    b.ConverterParameter = jArray[i].ToString().Replace("\"","");
                    b.Converter = (IValueConverter)new RowIndexConverter();
                    column.Header = jArray[i].ToString().Replace("\"", "");
                    column.Binding = b;
                    dataGrid.Columns.Add(column);
                }
                
                var rows = new System.Collections.ObjectModel.ObservableCollection<Row>();
                if (!jObject.ContainsKey("recordset"))
                    return;
                jArray = (JsonArray)jObject["recordset"];
                for (int i = 0; i < jArray.Count; i++)
                {
                    Row row = new Row();
                    JsonArray jSubArray = (JsonArray)jArray[i];
                    for (int j = 0; j < jSubArray.Count; j++)
                    {
                        row[dataGrid.Columns[j].Header.ToString()] = jSubArray[j].ToString().Replace("\"", "");
                    }
                    rows.Add(row);
                }
                dataGrid.ItemsSource = rows;
                DataBindingCompleted();
                
            }
        }
    }
}
